package com.example.malltest0.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.malltest0.Vo.HotVo;
import com.example.malltest0.common.utils.RedisUtils;
import com.example.malltest0.common.utils.RequestUtil;
import com.example.malltest0.mbg.model.Platform;
import com.example.malltest0.service.HotService;
import com.example.malltest0.service.PlatformService;
import com.example.malltest0.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class HotServiceImpl implements HotService {

    @Autowired
    private RedisService redisService;

    @Autowired
    private PlatformService platformService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RequestUtil requestUtil;

    @Override
    public List<List<String>> getHot() {
        String lastUpdate = redisService.get("lastUpdate");
        List<Platform> platforms = platformService.selectAllPlatform();
        int size=platforms.size();
        long l = System.currentTimeMillis();
        long l1 = lastUpdate==null?0:Long.parseLong(lastUpdate);
        List<List<String>> hot = new ArrayList<>();
        if(l-l1>5*60*1000){

            System.out.println("热点已过期");
             hot = requestUtil.getHot();
            for (int i = 0; i < size; i++) {
                int size0=hot.get(i)==null?0:hot.get(i).size();
                for (int j = 0; j < size0; j++) {
                    redisUtils.lPush(platforms.get(i).getName(),JSON.toJSONString(hot.get(i).get(j)));
                }
            }
            redisService.set("lastUpdate",System.currentTimeMillis()+"");
            return hot;
        }
        else {
            System.out.println("热点未过期");
            for (int i = 0; i < size; i++) {
                List<Object> objects = redisUtils.lRange(platforms.get(i).getName(), 0, -4);
                List<String> strs = objects.stream().map(obj-> (String) obj).collect(Collectors.toList());
                hot.add(strs);
            }
        }
        return hot;
    }

    @Override
    public List<List<HotVo>> updateHot() {

        return null;
    }


}
